from window import *
from questionWindow import *
from strWindow import *
import network
import ujson
from util import display,drawImageFile

class WiFiWindow(Window):
	def __init__(self):
		Window.__init__(self)
		self.essid = ""
		self.password = ""
		self.loadWIFIconfig()
		self.save = 0
		if self.essid:
			self.btn_reset = Button("Reset",30,55,46,12)
			self.btn_reset.cb_hold = self.cb_reset
			Window.add(self,self.btn_reset)

			self.btn_connect = Button("<->",68,55,30,12)
			self.btn_connect.cb_hold = self.cb_connect
			Window.add(self,self.btn_connect)
		else:
			self.essid = "BC-ffffff"
			self.password = "00000000"

			self.btn_essid = Button("SSID:",28,25,48,12)
			self.btn_essid.cb_hold = self.cb_essid
			Window.add(self,self.btn_essid)

			self.btn_password = Button("PASS:",28,40,48,12)
			self.btn_password.cb_hold = self.cb_password
			Window.add(self,self.btn_password)

			self.btn_save = Button("Save",30,55,48,12)
			self.btn_save.cb_hold = self.cb_save
			Window.add(self,self.btn_save)

		self.btn_quit = Button("Quit",105,55,40,12)
		self.btn_quit.cb_hold = self.cb_quit
		Window.add(self,self.btn_quit)

		Window.setDrawCB(self,self.cb_draw)
		

		self.sta = network.WLAN(network.STA_IF)

	def run(self):
		self.save = 0
		Window.run(self)

	def loadWIFIconfig(self):
		f = open('wificonfig.json', 'r')
		content = f.read()
		wificonfig = ujson.loads(content)
		self.essid = wificonfig["essid"]
		self.password = wificonfig["password"]
		f.close()

	def cb_draw(self):
		display.text("Wifi Setting",0,0,1)
		display.text("SSID:",4,19,1)
		display.text("PASS:",4,34,1)
		display.text(self.essid,50,20,1)
		display.text(self.password,50,35,1)
		if self.sta.isconnected():
			drawImageFile('img/wifi.pb',110,0)
		if self.save:
			display.text("s",100,0,1)

	def cb_essid(self):
		self.save = 0
		w = SetStrWindow(tag="essid",default=self.essid)
		w.run()
		self.essid=w.value

	def cb_password(self):
		self.save = 0
		w = SetStrWindow(tag="passwd",default=self.password)
		w.run()
		self.password=w.value

	def cb_save(self):
		wificonfig = {
			"essid": self.essid,
			"password":self.password
		}
		jsonParam = ujson.dumps(wificonfig)
		f = open('wificonfig.json', 'w')
		f.write(jsonParam)
		f.close()
		self.save = 1

	def cb_connect(self):
		if not self.sta.isconnected():
			print('connecting to network...')
			self.sta.active(True)
			self.sta.connect(self.essid, self.password)
			print('network config:', self.sta.ifconfig())

	def cb_quit(self):
		self.save = 0
		Window.close(self)

	def cb_reset(self):
		wificonfig = {
			"essid": "",
			"password": ""
		}
		jsonParam = ujson.dumps(wificonfig)
		f = open('wificonfig.json', 'w')
		f.write(jsonParam)
		f.close()
		Window.close(self)